package com.xingfly.web;

import com.xingfly.security.jwt.util.JwtConstants;
import com.xingfly.security.jwt.util.JwtTokenUtil;
import com.xingfly.service.AccountService;
import com.xingfly.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.Date;

/**
 * Created by SuperS on 2016/12/1.
 */
@Controller
public class SecurityController {
    @Autowired
    private AccountService accountServer;
    @Autowired
    private CaptchaUtil captcha;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @GetMapping("/username")
    @ResponseBody
    public String username(Authentication authentication) {
        return authentication.getName();
    }

    @GetMapping("/permission")
    @ResponseBody
    public String permission(Authentication authentication) {
        return authentication.getAuthorities().toString();
    }


    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    @ResponseBody
    public String admin(Principal principal) {
        return "admin:" + principal.getName();
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/loginError")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login";
    }

    @GetMapping({"/home", "/"})
    public String home() {
        return "home";
    }


    @RequestMapping(value = "/img", method = RequestMethod.GET)
    public void captcha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        captcha.captcha(req, resp);
    }

    @PreAuthorize("hasRole('USER')")
    @GetMapping("/user")
    @ResponseBody
    public String user() {
        return "is User";
    }


    @GetMapping(value = "/code")
    @ResponseBody
    public String getGeneratedKey(HttpServletRequest req) {
        return captcha.getGeneratedKey(req);
    }

    @GetMapping(value = "/expiration")
    @ResponseBody
    public Date getExpirationDate(HttpServletRequest request) {
        return jwtTokenUtil.getExpirationDateFromToken(request.getHeader(JwtConstants.JWT_TOKEN_HEADER_PARAM));
    }


}
